package com.ruoyi.system.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.Material;
import com.ruoyi.system.domain.vo.MaterialVo;
import com.ruoyi.system.service.IMaterialService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/material")
public class MaterialController extends BaseController {
    @Autowired
    private IMaterialService materialService;

    @GetMapping("/list")
//    @RequiresPermissions("system:material:query")
    public TableDataInfo list(Material material){
        startPage();
        List<Material> materialList = materialService.getListByCondition(material);
        return getDataTable(materialList);
    }

    @PostMapping
//    @RequiresPermissions("system:material:add")
    @Log(title = "新增物料", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody Material material){
       return  toAjax(materialService.addMaterial(material));
    }

    @PutMapping
//    @RequiresPermissions("system:material:add")
    @Log(title = "修改物料", businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody Material material){
        return  toAjax(materialService.updateMaterial(material));
    }


    @GetMapping("/{id}")
    public AjaxResult getMaterialDetail(@PathVariable Long id){
        Material materialDetail = materialService.getMaterialDetail(id);
        System.out.println(materialDetail);
        if(StringUtils.isNoneEmpty(materialDetail.getMaterialImageUrl())){
            MaterialVo materialVo = new MaterialVo();
            BeanUtils.copyProperties(materialDetail,materialVo);
            String imageUrl = materialDetail.getMaterialImageUrl();
            String fileName = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
            materialVo.setFilePath(imageUrl);
            materialVo.setFileName(fileName);
            return AjaxResult.success(materialVo);
        }
        return AjaxResult.success(materialDetail);
    }

    /**
     * 删除物料
     */
//    @RequiresPermissions("system:user:remove")
    @Log(title = "物料删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable("ids") Long[] ids) {
        return toAjax(materialService.deleteMaterialByIds(ids));
    }

}
